﻿using DevelopTool.Common;
using DevelopTool.Forms.CommonHelpers;
using DevelopTool.Forms.LodingForm;
using DevelopTool.Forms.Properties;
using DevelopTool.Model.Enums;
using Miniblink;
using Sunny.UI;
using System;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Windows.Forms;

namespace DevelopTool.Forms.CommonControls
{
    public partial class MarkdownEditorControl2 : UIUserControl
    {
        #region 公有属性

        /// <summary>
        /// 编辑器模式，wysiwyg=所见即所得，ir=即时渲染，sv=分屏预览
        /// </summary>
        private string editorMode = "wysiwyg";

        /// <summary>
        /// 编辑器模式，wysiwyg=所见即所得，ir=即时渲染，sv=分屏预览
        /// </summary>
        [Description("编辑器模式，wysiwyg=所见即所得，ir=即时渲染，sv=分屏预览")]
        [Category("DevelopTool")]
        public string EditorMode
        {
            get
            {
                return this.editorMode;
            }
            set
            {
                this.editorMode = value;
            }
        }

        /// <summary>
        /// 文件路径或文件内容
        /// </summary>
        private string fileContent = "";

        /// <summary>
        /// 文件路径或文件内容
        /// </summary>
        [Description("文件路径或文件内容")]
        [Category("DevelopTool")]
        public string FileContent
        {
            get
            {
                return this.fileContent;
            }
            set
            {
                this.fileContent = value;
            }
        }


        /// <summary>
        /// 是否可编辑
        /// </summary>
        private bool isCanEdited = true;

        /// <summary>
        /// 是否可编辑
        /// </summary>
        [Description("是否可编辑")]
        [DefaultValue(value: true)]
        [Category("DevelopTool")]
        public bool IsCanEdited
        {
            get
            {
                return this.isCanEdited;
            }
            set
            {
                this.isCanEdited = value;
            }
        }

        /// <summary>
        /// 是否显示大纲
        /// </summary>
        private bool outline = false;

        /// <summary>
        /// 是否显示大纲
        /// </summary>
        [Description("是否显示大纲")]
        [DefaultValue(value: false)]
        [Category("DevelopTool")]
        public bool Outline
        {
            get
            {
                return this.outline;
            }
            set
            {
                this.outline = value;
            }
        }
        #endregion 公有属性

        #region 事件

        public delegate void NeedChangeControlTitleHandler(string title);

        /// <summary>
        /// 需要改变窗口标题时触发的事件
        /// </summary>
        [Description("需要改变窗口标题时触发的事件"), Category("DevelopTool")]
        public event NeedChangeControlTitleHandler OnNeedChangeControlTitle;

        #endregion 事件

        public MarkdownEditorControl2()
        {
            InitializeComponent();
        }


        private void MarkdownEditorControl2_Load(object sender, EventArgs e)
        {
            miniblinkWebBrowserControl.Browser.KeyDown += miniblinkBrowser_KeyDown;

            string vditorPath = Path.Combine(GlobalData.LocalUserDirectory, "vditor", "index.html");
            //将vditor编辑器组件解压到程序存储目录 MiniblinkWebBrowserControl
            if (!File.Exists(vditorPath))
            {
                LoadingHelper.ShowLoading("首次使用需要加载编辑器组件，请稍后", () =>
                {
                    ZipHelper.DecompressZipFileToDir(Resources.vditor, Path.GetDirectoryName(vditorPath));
                });
            }

            string param = $"?mode={this.editorMode}&isCanEdited={(isCanEdited == true ? 1 : 0)}&outline={(outline == true ? 1 : 0)}";

            this.miniblinkWebBrowserControl.Browser.LoadUri(vditorPath + param);//展示编辑器
            this.miniblinkWebBrowserControl.Browser.RegisterJsFunc(this);//注册js方法
        }


        /// <summary>
        /// 从页面调用。表示页面文档加载完成
        /// </summary>
        [JsFunc]
        private void DocumentIsReady()
        {
            string content = string.Empty;
            if (!string.IsNullOrEmpty(this.fileContent))
            {
                if (File.Exists(this.fileContent))//文件路径
                {
                    content = File.ReadAllText(this.fileContent);
                }
                else
                {
                    content = this.fileContent;//文件内容
                }

                this.miniblinkWebBrowserControl.Browser.CallJsFunc("setContent", content);
            }

        }


        /// <summary>
        /// 从页面调用。打开文件
        /// </summary>
        [JsFunc]
        private void OpenFile()
        {
            if (!Dialogs.OpenFileDialog(ref this.fileContent)) return;
            string content = File.ReadAllText(this.fileContent);
            this.miniblinkWebBrowserControl.Browser.CallJsFunc("setContent", content);
        }

        /// <summary>
        /// 绑定快捷键
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void miniblinkBrowser_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e)
        {
            //ctrl+s 保存
            if (e.KeyData == (Keys.S | Keys.Control))
            {
                Save();
            }

            //ctrl+shift+o 打开文件
            if (e.KeyData == (Keys.O | Keys.Control | Keys.Shift))
            {
                OpenFile();
            }

            //ctrl+shift+s 文件另存为
            if (e.KeyData == (Keys.S | Keys.Control | Keys.Shift))
            {
                SaveAs();
            }
        }

        /// <summary>
        /// 获取编辑器markdown内容
        /// </summary>
        /// <returns></returns>
        private string GetMDContent()
        {
            return this.miniblinkWebBrowserControl.Browser.CallJsFunc("getMDContent").ToString().TrimEnd(new char[] { '\n' });
        }

        /// <summary>
        /// 获取编辑器html内容
        /// </summary>
        /// <returns></returns>
        private string GetHTMLContent()
        {
            return this.miniblinkWebBrowserControl.Browser.CallJsFunc("getHTMLContent").ToString().TrimEnd(new char[] { '\n' }); ;
        }


        /// <summary>
        /// 保存文件
        /// </summary>
        [JsFunc]
        private void Save()
        {
            if (!isCanEdited) return;//不可编辑时直接返回

            if (File.Exists(this.fileContent))//文件路径
            {
                string content = GetMDContent();

                if (Path.GetExtension(this.fileContent).ToLower() == ".html")
                {
                    content = GetHTMLContent();
                }
                FileHelper.WriteFile(this.fileContent, content);

                UIMessageTip.ShowOk(this.miniblinkWebBrowserControl.Browser, "保存成功", 400, true);
            }
            else//文件内容
            {
                SaveAs();
            }
        }


        /// <summary>
        /// 文件另存为
        /// </summary>
        [JsFunc]
        public void SaveAs()
        {
            string content = GetMDContent();

            if (string.IsNullOrEmpty(content)) return;

            string filter = "Markdown文档|*.md|HTML|*.html|任何格式|*.*";
            string fileName = "";
            if (!Dialogs.SaveFileDialog(ref fileName, filter)) return;
            if (string.IsNullOrEmpty(fileName)) return;

            if (Path.GetExtension(fileName).ToLower() == ".html")
            {
                content = GetHTMLContent();
            }

            FileHelper.WriteFile(fileName, content);

            this.fileContent = fileName;
            UINotifierHelper.ShowNotifier($"保存成功", UINotifierType.OK, UIStyles.CurrentResources.OK, false, 2000);
        }

        /// <summary>
        /// 用默认程序打开
        /// </summary>
        [JsFunc]
        public void OpenWithDefaultProgram()
        {
            string filePath = string.Empty;

            string extension = "";

            string content= this.fileContent.Clone().ToString();

            if (string.IsNullOrEmpty(content))
            {
                content = GetMDContent();
            }

            //根据文件内容简单判断下文件类型，可能不准确
            ContentType contentType = MarkdownHelper.GetContentType(content);

            if (contentType == ContentType.FilePath)//文件
            {
                filePath = content;
            }
            else
            {
                if (contentType == ContentType.Markdown)//markdown文件
                {
                    extension = ".md";
                }
                else if (contentType == ContentType.HTML)//html文件
                {
                    extension = ".html";
                }
                else//未知文件类型
                {
                    extension = ".txt";
                }

                filePath = Path.Combine(DirectoryHelper.GetTempDirName(), $"{Path.GetFileNameWithoutExtension(this.Text)}{extension}");
                FileHelper.WriteFile(filePath, content);
            }

            Process.Start(filePath);//用系统默认的程序打开
        }

        /// <summary>
        /// 打印预览
        /// </summary>
        [JsFunc]
        public void Print()
        {
            UIMessageTip.Show(this.miniblinkWebBrowserControl.Browser, "未实现");
        }

        /// <summary>
        /// 关于
        /// </summary>
        [JsFunc]
        public void About()
        {
            AboutHelper.ShowAbout();
        }
    }
}
